from django.http import HttpResponse
from django.shortcuts import render
from .forms import MessageBoardForm,RegisterForm
#请求验证装饰器
from django.views.decorators.http import  require_http_methods

# Create your views here.
@require_http_methods(['GET','POST'])
def index(request):
    #如果用GET请求，那么就直接返回一个页面
    if request.method == 'GET':
        form = MessageBoardForm()
        return render(request,'index.html',context={'form':form})
    # elif request.method == 'POST':  因为用了请求验证装饰器，所以这句可以改成else了，@require_http_methods(['GET','POST'])设置了2种请求方式，不是GET就是POST.
    else:
        form = MessageBoardForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            email = form.cleaned_data.get('email')
            return HttpResponse(f"{title},{content},{email}")
        else:
            print(form.errors)
            return HttpResponse('表单验证失败！')

@require_http_methods(['GET','POST'])
def register_view(request):
    if request.method == 'GET':
        return render(request,'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data.get('telephone')
            return HttpResponse(telephone)
        else:
            print(form.errors)
            return HttpResponse('表单验证错误！')